package com.sugon.aop;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.utils.RRException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;

/**
 * 非业务参数校验-切面处理类
 *
 * @author YuXD
 * @date 2020-09-27 10:35
 */
@Aspect
@Component
public class NonBusinessParamValidAspect {

    /**
     * 只用作定义非业务参数校验切点，注解注明核心内容
     * 方法体内无需任何实现
     */
    @Pointcut("@annotation(com.sugon.annotation.NonBusinessParamValid)")
    public void nonBusinessParamValidPointcut() {
    }

    /**
     * 非业务参数校验before切面
     *
     * @param point
     * @throws Throwable
     */
    @Before("nonBusinessParamValidPointcut()")
    public void dataFilter(JoinPoint point) throws Throwable {
        // 参数不能为空且至少有两个参数
        Object[] args = point.getArgs();
        if (ArrayUtil.isEmpty(args) || args.length < 2) {
            return;
        }
        Object objArgs = args[1];
        if (objArgs instanceof BindingResult) {
            BindingResult validResult = (BindingResult) objArgs;
            // 基础校验是否通过
            if (validResult.hasErrors()) {
                StringBuilder sb = new StringBuilder();
                List<FieldError> fieldErrors = validResult.getFieldErrors();
                if (CollectionUtil.isNotEmpty(fieldErrors)) {
                    for (FieldError fieldError : fieldErrors) {
                        sb.append(",").append(fieldError.getDefaultMessage());
                    }
                }
                String validResultMsg = sb.toString();
                if (StrUtil.isNotEmpty(validResultMsg)) {
                    throw new RRException(validResultMsg.replaceFirst(",", ""));
                }
            }
        }
    }

}
